#include <nice2d/texthelper.h>

bool charInBounds(sf::Text &text, size_t pos, int width)
{
    return (text.findCharacterPos(pos).x + text.getCharacterSize() * 1.5 - text.findCharacterPos(
                0).x < width);
}

void TextHelper::wrapText(sf::Text &text, int32_t width)
{
    sf::String string = text.getString();
    std::wstring toWrap = string.toWideString();
    std::wstring wrapped;

    size_t epos = 1;

    while (epos < toWrap.size()) {
        if (!charInBounds(text, epos, width)) {
            bool space = true;
            unsigned int tpos = epos;
            while (toWrap.at(--epos) != L' ') {
                if (epos == 0 || toWrap.at(epos) == L'\n') {
                    space = false;
                    break;
                }
            }
            if (space) {
                wrapped += toWrap.substr(0, epos) + L"\n";
                toWrap.erase(epos, 1);
            } else {
                epos = tpos;
                while (!charInBounds(text, epos, width)) {
                    epos--;
                }
                //toWrap.insert(--epos, L"-");
                wrapped += toWrap.substr(0, ++epos) + L"\n";
            }
            toWrap = toWrap.substr(epos);
            epos = 0;
            continue;
        }
        epos++;
    }

    wrapped += toWrap;
    text.setString(wrapped);
}
